package com.xhh.nphm.web.controller.common;

import com.xhh.nphm.common.config.NphmConfig;
import com.xhh.nphm.common.config.ServerConfig;
import com.xhh.nphm.common.constant.Constants;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.common.core.domain.entity.SysUser;
import com.xhh.nphm.common.utils.StringUtils;
import com.xhh.nphm.common.utils.file.FileUploadUtils;
import com.xhh.nphm.common.utils.file.FileUtils;
import com.xhh.nphm.gaoxin.entity.GxqTelExcel;
import com.xhh.nphm.gaoxin.entity.GxqTtelGetDealEty;
import com.xhh.nphm.gaoxin.entity.GxqTworkFormBaseEty;
import com.xhh.nphm.gaoxin.service.GxqITelGetDealService;
import com.xhh.nphm.system.domain.MailExcel;
import com.xhh.nphm.system.domain.TelExcel;
import com.xhh.nphm.system.domain.TtelGetDealEty;
import com.xhh.nphm.system.domain.TworkFormBaseEty;
import com.xhh.nphm.system.service.ITelGetDealService;
import com.xhh.nphm.system.service.IWorkFormBaseService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 通用请求处理
 *
 * @author ydq
 */
@Controller
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    private static final String FILE_DELIMETER = ",";

    @Autowired
    private IWorkFormBaseService workFormBaseService;

    @Autowired
    private ITelGetDealService telGetDealService;

    @Autowired
    private GxqITelGetDealService GxqITelGetDealService;

    /**
     * 隐藏电话
     * @param user
     * @param
     * @return
     */
    public TworkFormBaseEty hidetTel(SysUser user, TworkFormBaseEty tworkFormBaseEty) {
        //隐藏电话号码 0不隐藏 5隐藏
        if(!"304".equals(user.getDeptId()) && "承办单位".equals(user.getSortName())) {
            TtelGetDealEty ttelGetDealEty = telGetDealService.getById(tworkFormBaseEty.getGetDealPk());
            if(ttelGetDealEty != null) {
                Integer hideTel = ttelGetDealEty.getHideTel();
                if(hideTel != null && hideTel.equals(5)) {
                    tworkFormBaseEty.setFromTelA(tworkFormBaseEty.getFromTelA().substring(0,3)+"****");
                    System.out.println(tworkFormBaseEty.getFromTelA());
                }
            }
        }
        return tworkFormBaseEty;
    }

    public GxqTworkFormBaseEty hidetTel_gxq(SysUser user, GxqTworkFormBaseEty tworkFormBaseEty) {
        //隐藏电话号码 0不隐藏 5隐藏
        if(!"304".equals(user.getDeptId()) && "承办单位".equals(user.getSortName())) {
            GxqTtelGetDealEty ttelGetDealEty = GxqITelGetDealService.getById(tworkFormBaseEty.getGetDealPk());
            if(ttelGetDealEty != null) {
                Integer hideTel = ttelGetDealEty.getHideTel();
                if(hideTel != null && hideTel.equals(5)) {
                    tworkFormBaseEty.setFromTelA(tworkFormBaseEty.getFromTelA().substring(0,3)+"****");
                    System.out.println(tworkFormBaseEty.getFromTelA());
                }
            }
        }
        return tworkFormBaseEty;
    }

    /**
     * 隐藏电话2
     * @param user
     * @return
     */
    public TelExcel hidetTel2(SysUser user, TelExcel t) {
        //隐藏电话号码 0不隐藏 5隐藏
        if(!"304".equals(user.getDeptId()) && "承办单位".equals(user.getSortName())) {
            if(t != null) {
                Integer hideTel = t.getHideTel();
                if(hideTel != null && hideTel.equals(5)) {
                    if(t.getFromTel().length() > 3) {
                        t.setFromTel(t.getFromTel().substring(0, 3) + "****");
                    }
                }
            }
        }
        return t;
    }

    /**
     * 隐藏电话2
     * @param user
     * @return
     */
    public GxqTelExcel hidetTel2_gxq(SysUser user, GxqTelExcel t) {
        //隐藏电话号码 0不隐藏 5隐藏
        if(!"304".equals(user.getDeptId()) && "承办单位".equals(user.getSortName())) {
            if(t != null) {
                Integer hideTel = t.getHideTel();
                if(hideTel != null && hideTel.equals(5)) {
                    if(t.getFromTel().length() > 3) {
                        t.setFromTel(t.getFromTel().substring(0, 3) + "****");
                    }
                }
            }
        }
        return t;
    }


    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("common/download")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = NphmConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/common/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            String directoryPath = "D:\\nphm\\uploadPath";
            File files = new File(directoryPath);
            if (!files.exists()){
                //创建文件夹
                if (files.mkdirs()){
                    System.out.println("创建" + directoryPath + "成功");
                } else {
                    System.out.println("创建" + directoryPath + "失败");
                }
            }
            // 上传文件路径
            String filePath = NphmConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileName", fileName);
            ajax.put("url", fileName);
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/common/uploads")
    @ResponseBody
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
        try {
            // 上传文件路径
            String filePath = NphmConfig.getUploadPath();
            List<String> fileNames = new ArrayList<String>();
            List<String> urls = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                fileNames.add(fileName);
                urls.add(url);
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 本地资源通用下载
     */
    @GetMapping("/common/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = NphmConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
}
